
 package myjavaapplication1;
import java.util.*;
   import java.io.*;
   import java.lang.*;
   import javax.swing.JDialog;
   import javax.swing.JOptionPane;

    public class DecodeSensorDownlink
   {
      
      public static String[] down = new String[200];  //this is the size of the (biggest) downlink packet/package. If not all is used the rest of the values will be null
      public static String[] easy = new String[20]; //this number can be bigger it is just the number of data points
      public static int count = 0;
      public static int carryover = 0;
   	
       public static void main(String [] args)
      {
           Convert();
        }
       public static void Convert()
        {
      
         //String[] hex = {"0","6","3","1", ",", "1","0", "1","9", "6","8", "0","1", "0","0", "0","2", "1","0", "1","8", "5","8", "0","1", "0","0", "0","F"}; //for now  as test data (this does not include 18b20 data)
         String[] hex = {"9","9","0","6","3","1", ",", "1","0", "1","9", "6","8", "0","1", "0","0", "0","2", "1","0", "1","8", "5","8", "0","1", "0","0", "0","F"}; //for now
         down = hex; 
      
      
         String[] copy = down;
                                             
         String[] fill = new String[29];  //this the number of chars of one complete set of data  //109 usually but 29 for now
         if(down[4].compareTo(",") != 0)   //if the packet is in the standard right order do stuff else shift the data so it is correct
         {
            //fill[]?
            int index = 0;
            for(int x=0; x<down.length; x++)
               if (down[x].compareTo(",") ==0)
               {
                  index = x;
                  break;  
               }
         
            int y=0;
            for(int x=index-4; x<index+25; x++) //index +104 or 105  //this formats the actual data minus the timestamp/comma
            {
               //System.out.println(y +" / " + x);
               if(x<=down.length)
                  fill[y] = down[x];
               else
                  carryover = x;
               y++;
            }
         
         }
         else
         {
            for(int x=0; x<fill.length; x++)
               fill[x] = down[x];
            
            down = fill;
         }
      	
         if(carryover != 0)   //this accounts for some sort of carry over. e.g. If in 2 packets there is 3 sets of complete data..  //may not be used or necessary
         {
            for(int x=carryover; x<fill.length; x++)
            {
               fill[x] = copy[x];
            }
            carryover = 0;
            down = fill;
         }
         else
            down = fill;
      	
         
         count = 0;
         String time = getTimeStamp(down);    //each of these methods uses other methods that parse data based on the data sheet and then put it into an array.
         getTemp(down);      
         getVolt(down);    
         getCurrent(down);    
        
         //System.out.println(time);

         int numb = 0;
            while( new File("Sens" + numb +".txt").exists())   //consecutively adds .txt files
               numb++;

         printS(easy, numb);
       /*  for(int x = 0; x< easy.length; x++)
         {
            if(easy[x] != null)
            {
               System.out.println(easy[x]);
//////               printS(easy[x], numb);
             }
         }*/
      
      }
       public static void printS (String[] a, int n)
               {
           try
         {
            

        //int num = n;

            File file = new File("Sens" + n +".txt");
            PrintStream ps = new PrintStream(file);

           // String awesome = "";
            //for(int x=0; x<rx.length; x++)
              // awesome += (rx[x]) +"";

             for(int x = 0; x< a.length; x++)
         {
            if(a[x] != null)
            {
               System.out.println(a[x]);
               ps.print(a[x]);
               ps.print("\n"); //This \n seems to make a weird symbol when opening the txt file in Notepad.

             }
         }
            ps.close();

         }
             catch (Exception e)
            {
               System.out.println("wtf didnt do it; but add soem handling code");
            }
       }

       public static String getTimeStamp(String[] nums)
      {
         String stamp = "";
         stamp = nums[0] + nums[1] + nums[2] + nums[3];
         easy[count] = stamp;
         count++;
         return stamp;
      
      }
       public static void getTemp(String[] nums)
      {
          //count = 0;
         String t = "";
         String place ="X+ = ";				//this is like where each sensor is on/in the cube. See the balsa satellite for how they each side is labeled.
         for(int x=5; x<nums.length; x+=12)  //change this to nums.length-12 or something cuz its only 2438s
         {
            if(x == 17)							//every time in the packet the sensors are in the same order so starting at lets say index 17, we could identify it as the one on side +Y or whatever
               place = "Y+ = ";
            t = nums[x] + nums[x+1] + nums[x+2] + nums[x+3];
            t = place + convertTemp(t) + "  deg C";
            easy[count] = t;
            count++;
         }
         
         t = "";
         for(int x=96; x<nums.length; x+=4)  //for the18b20s    //96 or 101
         {
         /*
          t = nums[x] + nums[x+1] + nums[x+2] + nums[x+3];
          t = "Temp## = " + convertTempzors(t) + "  deg C";	 
          easy[count] = t;
         count++;
                  */
         }
      
      }
       public static void getVolt(String[] nums)
      {
         //int count = 0;
         String t = "";
         String place ="X+ = ";
         for(int x=9; x<nums.length; x+=12)  //change this to nums.length-12 or something cuz its only 2438s
         {
            if(x == 21)
               place = "Battery = ";
            t = nums[x] + nums[x+1] + nums[x+2] + nums[x+3];
            t = place + convertVolt(t) + "  volts";
            easy[count] = t;
            count++;
         }
      
      }
       public static void getCurrent(String[] nums)
      {
         String t = "";
         for(int x=13; x<nums.length; x+=12)  //change this to nums.length-12 or something cuz its only 2438s
         {
            t = nums[x] + nums[x+1] + nums[x+2] + nums[x+3];
            t = "Curr# = " + convertCurrent(t) + "  mA or A ?";
            easy[count] = t;
            count++;
         }
      
      }
       public static String convertTemp(String t)
      {
      
         String[] split = {t.substring(0,2), t.substring(2,t.length())};
         //System.out.println(split[0] + " " + split[1]);  //tb
      
        //temperature lsb
         int i = Integer.parseInt(split[0], 16);
         String binarylsbtemp = Integer.toBinaryString(i);
        // System.out.println(binarylsbtemp);////tb
         int length = binarylsbtemp.length();
         for(int x =0; x< (8 -length); x++)           ///adds the correct number of zeroes to the binary string   for consistent parsing
         {
            binarylsbtemp = "0" + binarylsbtemp;
         }
         //System.out.println(binarylsbtemp);////tb   
        
         double lowtemp = 0;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(0)+"")) * (Math.pow(2,-1)) ;   //this might be a little confusing but charAt(0) would really be like the 'last' bit (bit7) becasue they lable them backwards
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(1)+"")) *(Math.pow(2,-2)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(2)+"")) *(Math.pow(2,-3)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(3)+"")) *(Math.pow(2,-4)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(4)+"")) *(Math.pow(2,-5)) ;
         //System.out.println(lowtemp);////tb
      
            //temperature msb	
         int j = Integer.parseInt(split[1], 16);
         String binarymsbtemp = Integer.toBinaryString(j);
         length = binarymsbtemp.length();
         for(int x =0; x< (8 -length); x++)   
         {
            binarymsbtemp = "0" + binarymsbtemp;
         }	
         //System.out.println(binarymsbtemp);////tb
         
      																					//the sign character is just a bit or more that inverts other bits (ie 1 becomes 0) signaling the value is negative
      	//sign char messes things up                                                 //for some reason the lsb bits also change but I dont know how?
         boolean sign =false;
         if(Integer.parseInt(binarymsbtemp.charAt(0)+"")  ==1)
         {
            String signbinarytemp = binarymsbtemp;
            binarymsbtemp = "";
            sign = true;
            for(int x =0; x<signbinarytemp.length(); x++)  
               if(Integer.parseInt(signbinarytemp.charAt(x)+"")  ==1)
                  binarymsbtemp += "0";
               else
                  binarymsbtemp += "1";
         }
         //System.out.println(binarymsbtemp);////tb
      
         double hightemp = 0;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(1)+"")) *(Math.pow(2,6)) ;  //0 bit is sign char      
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(2)+"")) *(Math.pow(2,5)) ;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(3)+"")) *(Math.pow(2,4)) ;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(4)+"")) *(Math.pow(2,3)) ;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(5)+"")) *(Math.pow(2,2));
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(6)+"")) *(Math.pow(2,1)) ;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(7)+"")) *(Math.pow(2,0)) ;
         ///System.out.println(hightemp);////tb
          
         double result = (hightemp + lowtemp);
         if(sign)
            result = (result * (-1));
      	
         if(result > 125)  //accounts for the precision of the chip
            result = 125;
         if (result < -55)
            result = -55;
      	
         //System.out.println(result + "  degrees C");
         String qq = "" + result;
         return qq;
            
      }
       public static String convertTempzors(String t)     //this is almost the same as convertTemp but this is for the 18b20
      {
         //String[] split = {t.substring(0,2), t.substring(2,t.length())};
         //System.out.println(split[0] + " " + split[1]);  //tb
      
         String[] split = {"91", "10"};
         
      	 //temperature msb	
         int j = Integer.parseInt(split[1], 16);
         String binarymsbtemp = Integer.toBinaryString(j);
         int length1 = binarymsbtemp.length();
         for(int x =0; x< (8 -length1); x++)   
         {
            binarymsbtemp = "0" + binarymsbtemp;
         }	
         //System.out.println(binarymsbtemp);////tb
        
       //temperature lsb
         int i = Integer.parseInt(split[0], 16);
         String binarylsbtemp = Integer.toBinaryString(i);
        // System.out.println(binarylsbtemp);////tb
         int length2 = binarylsbtemp.length();
         for(int x =0; x< (8 -length2); x++)           ///adds the correct number of zeroes to the binary string
         {
            binarylsbtemp = "0" + binarylsbtemp;
         }
         //System.out.println(binarylsbtemp);////tb   
        
            //sign char messes things up                                          
         boolean sign =false;
         if(Integer.parseInt(binarymsbtemp.charAt(0)+"")  ==1)  //if theres a runtime error for this section - its likely in this loop
         {
            sign = true;
         
            String signbinarytemp = binarymsbtemp;
            binarymsbtemp = "";
            for(int x =0; x<signbinarytemp.length(); x++)  
               if(Integer.parseInt(signbinarytemp.charAt(x)+"")  ==1)
                  binarymsbtemp += "0";
               else
                  binarymsbtemp += "1";
                  
            signbinarytemp = binarylsbtemp;
            binarylsbtemp = "";
            for(int x =0; x<signbinarytemp.length(); x++)  
               if(Integer.parseInt(signbinarytemp.charAt(x)+"")  ==1)
                  binarylsbtemp += "0";
               else
                  binarylsbtemp += "1";
         }
         //System.out.println(binarymsbtemp);////tb  
        
         double lowtemp = 0;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(0)+"")) * (Math.pow(2,3)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(1)+"")) *(Math.pow(2,2)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(2)+"")) *(Math.pow(2,1)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(3)+"")) *(Math.pow(2,0)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(4)+"")) *(Math.pow(2,-1)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(5)+"")) *(Math.pow(2,-2)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(6)+"")) *(Math.pow(2,-3)) ;
         lowtemp += (Integer.parseInt(binarylsbtemp.charAt(7)+"")) *(Math.pow(2,-4)) ;
         	//System.out.println(lowtemp);////tb
      
         double hightemp = 0;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(5)+"")) *(Math.pow(2,6)) ;  //0 to 4 bits are sign chars     
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(6)+"")) *(Math.pow(2,5)) ;
         hightemp += (Integer.parseInt(binarymsbtemp.charAt(7)+"")) *(Math.pow(2,4)) ;
         ///System.out.println(hightemp);////tb
          
         double result = (hightemp + lowtemp);
         if(sign)
            result = (result * (-1));
      	
         if(result > 125)  //accounts for the precision of the chip
            result = 125;
         if (result < -55)
            result = -55;
      	
         //System.out.println(result + "  degrees C");
         String qq = "" + result;
         return qq;
      
      }
   
       public static String convertVolt(String t)
      { 
         String[] split = {t.substring(0,2), t.substring(2,t.length())};
       //voltage lsb
         double lowvolt = Integer.parseInt(split[0], 16);  //simple as that
         //System.out.println(lowvolt);////tb
        
        //volt msb
         int i = Integer.parseInt(split[1], 16);
         String binarymsbvolt = Integer.toBinaryString(i);
         int length = binarymsbvolt.length();
         for(int x =0; x< (8 -length); x++)   
         {
            binarymsbvolt = "0" + binarymsbvolt;
         }	
         //System.out.println(binarymsbvolt);////tb
      
         double highvolt = 0;
         highvolt += (Integer.parseInt(binarymsbvolt.charAt(7)+"")) * (Math.pow(2,8)) ;
         highvolt += (Integer.parseInt(binarymsbvolt.charAt(6)+"")) *(Math.pow(2,9)) ;
         
         double result = (highvolt + lowvolt);
         result = (result / 100);  //becasue it is in 10 millivolts units
        
       //System.out.println(result + "  volts");
         String qq = "" + result;
         return qq;
      } 
   	  
       public static String convertCurrent(String t)
      {
         String[] split = {t.substring(0,2), t.substring(2,t.length())};
      	   //current lsb
         double lowcur = Integer.parseInt(split[0], 16);  //simple as that
         //System.out.println(lowcur);////tb
        
        //current msb
         int i = Integer.parseInt(split[1], 16);
         String binarymsbcurrent = Integer.toBinaryString(i);
         int length = binarymsbcurrent.length();
         for(int x =0; x< (8 -length); x++)   
         {
            binarymsbcurrent = "0" + binarymsbcurrent;
         }	
         //System.out.println(binarymsbcurrent);////tb
      
         double highcur = 0;
         highcur += (Integer.parseInt(binarymsbcurrent.charAt(7)+"")) * (Math.pow(2,8)) ;
         highcur += (Integer.parseInt(binarymsbcurrent.charAt(6)+"")) *(Math.pow(2,9)) ;
         
         double result = (highcur + lowcur);
         double Rsense = 1.6;  //in ohms
         result = (result / (4096* Rsense));           //becasue of some random stuff, i think check page 5 of datasheet  //it measure current by (voltage / ohms)
        
        
         //System.out.println(result + "  amps or milliamps?");    //we converted voltage to current (I = V/R) but i forgot the units
         String qq = "" + result;
         return qq;
      
      }
       public static String convert2406(String t)
      {
      //assuming t is just the 2nd and 3rd to last characters/bits in the channel control byte returned (CHS0 + CHS1)(page 13 of datasheet). 
         if(t.charAt(0) == ('0') && t.charAt(1) == ('1'))
         {
            return "channel A high only";
         }
         else if(t.charAt(0) == ('1') && t.charAt(1) == ('0'))
            return "channel B high only";
         else if(t.charAt(0) == ('1') && t.charAt(1) == ('1'))
            return "channel A and B high ";
         else  if(t.charAt(0) == ('0') && t.charAt(1) == ('0'))
            return "error, not possible";
      
         return "should never get here";  //cuz it shouldnt
      }
   	  
   	  
   	  
   	  
   	  
   	  
   	  
   	  
   	  
   	  
   }
 
 
//BUGS
//some similar from convertsensordata.java   !
//account for 18b20 in for loops (len-12?)

//check what happens if two commas are found in downlink


